const sqlHelper = require('../persist/sqlHelper');
const logger = require('../logs/logger');

module.exports = {
    add(s) {
        var sql = `INSERT INTO MSG (BIZ, MID, IDX, TITLE, DIGEST, CREATION, SRC, COVOR, AUTHOR, UPDATEAT) 
        VALUES (?,?,?,?,?,?,?,?,?,?)`;
        var params = [s.biz, s.mid, s.idx, s.title, s.digest, s.creation, s.src, s.covor, s.author, s.updateAt];

        sqlHelper.execute(conn => {
            conn.query(sql, params, (err, resp) => {
                if (err) {
                    logger.exception(err);
                    return;
                }
                logger.debug(`INSERT MSG: ${JSON.stringify(resp)}`);
            });
        });
    },

    update(s) {
        var sql = `INSERT INTO MSG_EXT VALUES (?,?,?,?,?,?)`;
        var params = [s.biz, s.mid, s.idx, s.updateAt, s.likes, s.reads];

        sqlHelper.execute(conn => {
            conn.query(sql, params, (e, r) => {
                if (e) {
                    logger.exception(e);
                    return;
                }
                logger.debug(`INSERT MSG_EXT -> : ${JSON.stringify(r)}`);
            });
        });
    },

    async fetchOptions(subscription) {
        var days = await new Promise((resolve, reject) => {
            var sql = "SELECT LastDays FROM ScTask WHERE ID = (SELECT ScTaskId FROM ScDeviceTask WHERE SUBSCRIPTION = ? AND STATUS = 3 ORDER BY StartAt DESC LIMIT 1)";
            var params = [subscription];
            var lastDays = null;

            sqlHelper.execute(conn => {
                conn.query(sql,
                    params,
                    (err, resp) => {
                        if (err) {
                            logger.exception(err);
                            reject(err);
                        } else if (resp.length === 0) {
                            reject('resp.length === 0');
                        } else {
                            lastDays = resp[0].LastDays;
                            resolve(lastDays);
                        }
                    });
            });
        });

        return days;
    }
};